<template>
	<view :class="isRecord? 'recordBg emergencyHelp':'emergencyHelp'">
		<!-- 头部大文字 -->
		<view class="bigtitel">
			<view class="">
				严重危害生命财产安全
			</view>
			<view class="">
				求助专属通道
			</view>
		</view>
		<view class="tips">
			平台将为您：保留录音证据、实时位置、通知平台联系人
		</view>
		<view class="img" v-if="!isRecord">
			<image :src="imgUrl+'lyimg.png'" mode=""></image>

		</view>
		<view class="img" v-else>
			<image :src="imgUrl+'lyzimg.png'" mode=""></image>
		</view>
		<view v-if="!isRecord" class="btn" @click="startRecord">
			开始录音
		</view>
		<view v-else class="btn" @click="endRecord" style="color: #46D17E;">
			<!-- 录音中<br /> -->
			结束录音
		</view>
		<!-- 		<audio style="text-align: left" :src="current.src" :poster="current.poster" :name="current.name"
			:author="current.author" :action="audioAction" controls></audio> -->
		<!-- <view class="kefu" @click="play()()">
			播放
		</view> -->
		<view class="kefu" @click="call()">
			拨打110
		</view>
		<view class="footer-tisp">
			<view class="">
				当你感受到危险、生命财产受到威助

			</view>
			<view class="">
				侵害时请及时拨打110
			</view>
		</view>
		<file></file>
	</view>
</template>

<script>
	// const recorderManager = uni.getRecorderManager();
	// const innerAudioContext = uni.createInnerAudioContext();

	// innerAudioContext.autoplay = true;
	import {
		callPolice
	} from "./api.js";
	import Recorder from 'js-audio-recorder';
	import file from "../components/file/file.vue";
	const lamejs = require('lamejs')
	export default {
		components: {
			file
		},
		data() {
			return {
				// current: {
				// 	poster: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/music-a.png',
				// 	name: '致爱丽丝',
				// 	author: '暂无',
				// 	src: 'https://pw.zhijiayitong.com.cn/uploads/audio/20231222/c1defffe30d14148d109e29a6db7086a.mp3',
				// },
				// audioAction: {
				// 	method: 'pause'
				// },
				imgUrl: this.$store.state.imgUrl,
				audio: "", //保存的录音
				isRecord: false,
				longitude: '',
				latitude: '',
				province: '',
				city: '',
				district: '',
				address: '',
				recorder: '',
				filePath: '',
				base64Str: ''
			}
		},
		onLoad() {
			// 获取当前经纬度
			this.recorder = new Recorder()

			this.handleLocation()
			this.getAddress()
			let _this = this

			this.recorderManager = uni.getRecorderManager();
			this.innerAudioContext = uni.createInnerAudioContext();
			this.innerAudioContext.autoplay = true;
			this.recorderManager.onStop(function(res) {
				_this.uploadImg(res.tempFilePath)
			});

		},
		watch: {
			isRecord(newValue) {
				if (newValue) {
					uni.setNavigationBarColor({
						frontColor: '#ffffff',
						backgroundColor: '#0ca27d',
					})
				} else {
					uni.setNavigationBarColor({
						frontColor: '#ffffff',
						backgroundColor: '#f97302',
					})
				}
			}
		},
		methods: {
			// 开始录音
			start() {
				this.Recorder = new Recorder()
				Recorder.getPermission().then(() => {
					console.log('开始录音')
					this.isRecord = true
					this.recorder.start() // 开始录音
				}, (error) => {
					this.$message({
						message: '请先允许该网页使用麦克风',
						type: 'info'
					})
					console.log(`${error.name} : ${error.message}`)
				})
			},

			uploadWav() {
				let _this = this
				let file = _this.blobToFile(_this.recorder.getWAVBlob(), "1.wav")
				console.log("开始上传");
				console.log();
				console.log(file);
				uni.uploadFile({
					header: {
						token: _this.$db.get('token')
					},
					url: "https://pw.zhijiayitong.com.cn/api/upload",

					file: file,
					name: 'file',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes, 'uploadFileResuploadFileRes');
						console.log('/sys/common/static/scott/pic/' +
							JSON.parse(uploadFileRes.data).result);
					},
					complete: () => {},
					fail: (res) => {
						console.log(res)
					}
				})
			},
			stop() {
				let _this = this
				console.log('停止录音')
				_this.recorder.stop() // 停止录音
				console.log(_this.recorder, 'this.recorderthis.recorderthis.recorder');
				setTimeout(() => {
					let file = _this.blobToFile(_this.recorder.getWAVBlob(), "1.wav")
					console.log(file);
					this.getMp3Data()
				}, 1000)



			},
			play() {
				console.log('播放录音')
				console.log(this.recorder)
				this.recorder.play() // 播放录音

				// 播放时长
				this.timer = setInterval(() => {
					try {
						this.playTime = this.recorder.getPlayTime()
					} catch (error) {
						this.timer = null
					}

				}, 100)
			},
			blobToFile(theBlob, fileName) {
				//将blob转换为file  
				console.log(theBlob, 'hahahahahahahahh');
				let file = new File([theBlob], fileName, {
					type: theBlob.type.split('/')[1],
					lastModified: Date.now()
				});
				console.log(file);
				return file;
			},

			// blobToFile(theBlob, fileName) {
			// 	let file = new File([theBlob], fileName, {
			// 		type: theBlob.type.split('/')[1],
			// 		lastModified: Date.now()
			// 	});
			// 	return file;
			// },
			//手动设置地址
			handleLocation() {
				let _this = this
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						_this.longitude = res.longitude
						_this.latitude = res.latitude
					}
				});
			},
			convertToMp3(wavDataView) {
				// 获取wav头信息
				const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
				const {
					channels,
					sampleRate
				} = wav;
				const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
				// 获取左右通道数据
				const result = this.recorder.getChannelData()
				const buffer = [];

				const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
				const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
				const remaining = leftData.length + (rightData ? rightData.length : 0);

				const maxSamples = 1152;
				for (let i = 0; i < remaining; i += maxSamples) {
					const left = leftData.subarray(i, i + maxSamples);
					let right = null;
					let mp3buf = null;

					if (channels === 2) {
						right = rightData.subarray(i, i + maxSamples);
						mp3buf = mp3enc.encodeBuffer(left, right);
					} else {
						mp3buf = mp3enc.encodeBuffer(left);
					}

					if (mp3buf.length > 0) {
						buffer.push(mp3buf);
					}
				}

				const enc = mp3enc.flush();

				if (enc.length > 0) {
					buffer.push(enc);
				}
				const mp3Blob = new Blob([new Uint8Array(buffer)], {
					type: 'audio/mp3'
				});
				return mp3Blob;

				// return new Blob(buffer, {
				// 	type: 'audio/mp3'
				// });
			},



			zanshidow() {
				// 获取录音
				let blob = this.recorder.getPCMBlob();
				console.log(this.recorder.getPCMBlob())
				// blob转换成file对象
				let files = new window.File([blob], 'ex.mp3', {
					type: 'audio/mpeg'
				});
				console.log(blob.type)
				console.log(files, 'filesfilesfiles');
				// this.$refs.file.hRequest({
				// 	url: 'http://120.77.251.202:3000/Listen/listen',
				// 	file: files
				// });
				// console.log(files)
			},
			changeFormat(recorderData) {
				// new Int16Array(this.recorder.getWAV().buffer) 取录音的buffer
				const channels = 1; //1 单声道 2 立体声
				const sampleRate = 44100; //44.1khz
				const kbps = 128; //128kbps mp3
				var mp3encoder = new lamejs.Mp3Encoder(channels, sampleRate, kbps);
				var mp3Data = [];
				var samples = new Int16Array(recorderData.buffer); // 从源中获取数据
				const sampleBlockSize = 1152; //576的倍数
				for (var i = 0; i < samples.length; i += sampleBlockSize) {
					var sampleChunk = samples.subarray(i, i + sampleBlockSize);
					var mp3buf = mp3encoder.encodeBuffer(sampleChunk);
					if (mp3buf.length > 0) {
						mp3Data.push(mp3buf);
					}
				}
				var mp3buf = mp3encoder.flush(); //finish writing mp3
				if (mp3buf.length > 0) {
					mp3Data.push(new Int8Array(mp3buf));
				}
				var blob = new Blob(mp3Data, {
					type: 'audio/mp3'
				});
				return blob;
			},


			getMp3Data() {
				var that = this
				var wavBlob = that.recorder.getWAVBlob();
				console.log(wavBlob);
				let PCMBlob = that.recorder.getPCMBlob(); //获取 PCM 数据
				let file = this.blobToFile(that.recorder.getWAVBlob(), new Date().getTime() + "1.wav")
				// const mp3Blob = that.convertToMp3(that.recorder.getWAV());
				const mp3Blob = that.changeFormat(that.recorder.getWAV())
				console.log(mp3Blob, 'mp3Blobmp3Blobmp3Blob');
				let file1 = this.blobToFile(that.recorder.getPCMBlob(), new Date().getTime() + "1.pcm")
				let files = this.blobToFile(mp3Blob, new Date().getTime() + 'ex.mp3', {
					type: 'audio/mpeg'
				});
				console.log(files, 'filesfilesfiles');
				// let file = new File([mp3Blob], new Date().getTime() + 'ex.mp3', {
				// 	type: 'audio/mpeg'
				// })
				console.log(file, 'formDataformDataformDataformDatafilefilefile');
				console.log(file1, 'formDataformDataformDataformDatafilefilefile');
				// return
				// this.recorder.downloadWAV('新文件11');
				// uni.uploadFile({
				// 	url: 'https://pw.zhijiayitong.com.cn/api/uploadAudio',
				// 	// filePath: file,
				// 	file: file,
				// 	name: 'file',
				// 	header: {
				// 		// "Authorization": "xxx",
				// 		// 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryHEdN1AIjcdUkAaXM',
				// 	},

				// 	success: (uploadFileRes) => {
				// 		uni.showToast({
				// 			title: uploadFileRes.data.msg,

				// 		})
				// 	},
				// 	complete: () => {},
				// 	fail: (res) => {
				// 		console.log(res)
				// 	}
				// })
				console.log(that.$db.get('token'), '哈哈哈哈');
				uni.uploadFile({

					url: 'https://pw.zhijiayitong.com.cn/technician/uploadAudio',
					// filePath: file,
					file: file,
					name: 'file',
					header: {
						"technician-token": that.$db.get('token').token,
					},
					success: (uploadFileRes) => {
						uni.showToast({
							title: uploadFileRes.data.msg,
						})
					},
					complete: () => {},
					fail: (res) => {
						console.log(res)
					}
				})

				//上传语音

				// let blobpath = URL.createObjectURL(mp3Blob)
				// let formData = new FormData();


				// console.log(blobpath, 'blobpathblobpathblobpathblobpathblobpath');

				// uni.request({
				// 	url: 'https://pw.zhijiayitong.com.cn/api/uploadAudio', //仅为示例，并非真实接口地址。
				// 	header: {
				// 		token: that.$db.get('token'),
				// 		// 'Content-Type': 'multipart/form-data' //自定义请求头信息
				// 	},
				// 	data: {
				// 		file: blobpath,

				// 	},
				// 	method: 'POST',


				// 	success: (res) => {
				// 		console.log(res.data);
				// 		// this.text = 'request success';/*  */
				// 	}
				// });
				// this.recorder.downloadPCM('新文件');

				// this.recorder.download(mp3Blob, 'recorder', 'mp3')

			},
			uploadWAVData() {
				var wavBlob = this.recorder.getWAVBlob();
				// 创建一个formData对象
				var formData = new FormData()
				// 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
				const newbolb = new Blob([wavBlob], {
					type: 'audio/wav'
				})
				//获取当时时间戳作为文件名
				const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
				formData.append('file', fileOfBlob)
				console.log(formData);
				uploadWavData(formData).then((response) => {
					console.log(response);
				});

			},

			startRecord() {
				// this.isRecord = true
				this.start()
				// this.recorderManager.start({
				// 	format: "mp3"
				// });

			},
			endRecord() {
				let that = this
				this.isRecord = false
				console.log('录音结束');
				const formData = new FormData()

				this.stop()
			},

			//上传图片
			uploadImg(e) {
				// uni.showLoading({
				// 	title: '录音正在上传'
				// })
				let _this = this
				console.log(e);
				const xhr = new XMLHttpRequest();
				const url = 'https://pw.zhijiayitong.com.cn/api/upload';

				// uni.uploadFile({
				// 	url: 'https://pw.zhijiayitong.com.cn/api/upload',
				// 	filePath: e,
				// 	name: 'file',
				// 	header: {
				// 		token: _this.$db.get('token'),
				// 		'content-type': 'application/octet-stream'
				// 	},
				// 	success: (res) => {

				// 		var _data = JSON.parse(res.data);
				// 		if (_data.code == 200) {
				// 			_this.audio = _data.data.path
				// 			// _this.handleCallPolice()
				// 			console.log(_this.audio, "返回")
				// 		} else {
				// 			uni.showToast({
				// 				title: _data.msg,
				// 				icon: 'none'
				// 			})
				// 		}
				// 	}
				// });
			},

			getAddress() { //获取地址
				let _this = this
				uni.getLocation({
					altitude: false,
					geocode: true,
					type: 'gcj02',
					success: (res) => {
						console.log(res, "打印的res值获取city")
						_this.province = res.address.province
						_this.city = res.address.city
						_this.district = res.address.district
						_this.address = res.address.street + res.address.streetNum + res.address
							.poiName


					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			// 提交报警信息
			handleCallPolice() {
				let data = {
					province: this.province,
					city: this.city,
					district: this.district,
					address: this.address,
					audio: this.audio,
					longitude: this.longitude,
					latitude: this.latitude
				}
				let audio = this.audio
				console.log(data, '/*/*');
				callPolice(data).then(res => {
					uni.showToast({
						title: res.msg
					})
				})
			},
			call(e) {
				uni.makePhoneCall({
					phoneNumber: "110"
				});
			},
		}
	}
</script>

<style lang="less">
	.emergencyHelp {
		width: 100%;
		min-height: 100vh;
		background: #f97302;
		text-align: center;
		overflow-y: auto;

		.bigtitel {
			font-size: 40rpx;
			font-weight: bold;
			line-height: 64rpx;
			color: #FFFFFF;
			margin-top: 100rpx;
		}

		.tips {
			font-size: 24rpx;
			font-weight: 400;
			line-height: 64rpx;
			color: #FFFFFF;
		}

		.img {
			width: 488rpx;
			height: 488rpx;
			margin: 0 auto;
			margin-top: 80rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.btn {
			width: 176rpx;
			height: 176rpx;
			margin: 0 auto;
			background: linear-gradient(140deg, #FFFFFF 0%, #FFF0D6 100%);
			border-radius: 50%;
			font-size: 32rpx;
			font-weight: 500;
			line-height: 176rpx;
			color: #FFB83C;
			margin-top: 100rpx;
		}

		.footer-tisp {
			font-size: 24rpx;
			font-weight: 400;
			line-height: 44rpx;
			color: #FFFFFF;
			margin: 40rpx 0 60rpx 0;
		}
	}

	.recordBg {
		background: #0ca27d;
	}

	.kefu {
		width: 200rpx;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 0 auto;
		background-color: #FFB83C;
		margin-top: 60rpx;
		border-radius: 20rpx;
		color: #fff;

	}
</style>